package io.wit.common.exception;

import io.wit.common.utils.R;
import io.wit.tool.ToolClient;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理器
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月27日 下午10:16:19
*/
@RestControllerAdvice
public class RRExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 处理自定义异常
	*/
	@ExceptionHandler(RRException.class)
	public R handleRRException(RRException e){
		R r = new R();
		r.put("code", e.getCode());
		r.put("msg", e.getMessage());
		return r;
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public R handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return R.error("数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public R handleAuthorizationException(AuthorizationException e){
		logger.error(e.getMessage(), e);
		return R.error("没有权限,请联系管理员授权");
	}

    //认证异常,密钥认证过期
    @ExceptionHandler(ExpiredCredentialsException.class)
    public void expiredCredentialsException(final Exception exception,final HttpServletResponse response){
        exception.printStackTrace();
        ToolClient.responseJson(ToolClient.createJsonFail("无效的token"),response);
    }

    @ExceptionHandler(IncorrectCredentialsException.class)
    public void incorrectCredentialsException(final Exception exception,final HttpServletResponse response){
        exception.printStackTrace();
        ToolClient.responseJson(ToolClient.createJsonFail("账号或密码错误"),response);
    }

    @ExceptionHandler(UnauthorizedException.class)
    public void unauthorizedException(final Exception exception,final HttpServletResponse response){
        final String message = exception.getMessage();
        if(message.contains("Subject does not have role [")){
            //没有角色
        }else if(message.contains("Subject does not have permission [")){
            //没有权限
        }
        ToolClient.responseJson(ToolClient.createJsonFail("无操作权限"),response);
    }

    @ExceptionHandler(UnauthenticatedException.class)
    public void unauthenticatedException(final HttpServletResponse response){
        ToolClient.responseJson(ToolClient.invalidToken(),response);
    }

    @ExceptionHandler(Exception.class)
    public R exception(final Exception exception){
        exception.printStackTrace();
        return R.create(204,"系统出现错误");
    }
}